/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.yonsei.iwb.smarttv.querygraph;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QueryParseException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import edu.yonsei.iwb.smarttv.result.ResultNode;
import edu.yonsei.iwb.smarttv.result.ResultTypeInfo;
import edu.yonsei.iwb.smarttv.result.SearchResultSet;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 * @author JDK
 */
public class OntologySearchbySPARQL {

    Model model;

    public OntologySearchbySPARQL(Model model) {
        this.model = model;
    }

    public Vector<SearchResultSet> getSPARQLResult(Query query) {
        Vector<SearchResultSet> srs = new Vector<SearchResultSet>();
        try {
            Query q = QueryFactory.create(query);
            QueryExecution qe = QueryExecutionFactory.create(q, this.model);
            ResultSet results = qe.execSelect();
            
            Vector<Resource> existset = new Vector<Resource>();
            while (results.hasNext()) {
                QuerySolution qs = results.next();
                Iterator<String> is = qs.varNames();
                
                String varName = is.next();
                Resource r = qs.getResource(varName);
                if (!existset.contains(r)) {
                    existset.add(r);
                    ResultNode rn = new ResultNode(r);
                    ResultTypeInfo rtInfo = new ResultTypeInfo(r);
                    SearchResultSet sr = new SearchResultSet();
                    sr.setResult(rn);
                    sr.setResultTypes(rtInfo);
                    srs.add(sr);
                }
            }
            qe.close();
        } catch (QueryParseException e) {
            System.out.println(" - QueryParseException - \n \t --> Incorrect SPRAQL  \n");
            e.printStackTrace();
        }
        return srs;
    }
}
